import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/calendar_bottom_sheet.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/list_item/time_select_item.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:flutter/material.dart';

import 'default_bottom_sheet.dart';

/// 首页排序交易订单
showSortTransactionBottomSheet(BuildContext context, String sortTransaction,
    DateTime currentStartDate, DateTime currentEndDate) async {
  String _currentSelectCode = sortTransaction;
  final result = await showDefaultBottomSheet(
    context,
    child: SortTransactionBottomSheet(
      value: sortTransaction,
      startDate: currentStartDate,
      endDate: currentEndDate,
      selectCallBack: (data) {
        _currentSelectCode = data;
      },
    ),
    title: S.current.sort_transaction,
    isScrollControlled: true,
  );
  if (result != null) {
    return {
      'type': _currentSelectCode,
      ...(result as Map),
    };
  }
  return _currentSelectCode;
}

class SortTransactionBottomSheet extends StatefulWidget {
  final String value;
  final ValueChanged<String> selectCallBack;
  final DateTime startDate;
  final DateTime endDate;

  const SortTransactionBottomSheet(
      {Key key, this.value, this.selectCallBack, this.startDate, this.endDate})
      : super(key: key);

  @override
  _SortTransactionBottomSheetState createState() =>
      _SortTransactionBottomSheetState();
}

class _SortTransactionBottomSheetState
    extends State<SortTransactionBottomSheet> {
  List<String> sortTransactionList = [
    S.current.all_time,
    S.current.current_month,
    S.current.last_3_months,
    S.current.custom,
  ];

  String currentSelect;

  bool get isShowCustom => currentSelect == sortTransactionList.last;

  DateTime currentStartTime;
  DateTime currentEndTime;
  bool isOpenTimeSelect = false;

  bool get enable => currentStartTime != null && currentEndTime != null;

  @override
  void initState() {
    super.initState();
    currentSelect = widget.value;
    currentStartTime = widget.startDate;
    currentEndTime = widget.endDate;
  }

  void onChangeSalesTrend(String value) {
    if (currentSelect == value) return;
    setState(() {
      currentSelect = value;
    });
    if (currentSelect == sortTransactionList.last) {
    } else {
      widget.selectCallBack?.call(value);
      Navigator.of(context).pop();
    }
  }

  void _onSelectStartDate() async {
    setState(() {
      isOpenTimeSelect = true;
    });
    DateTime result = await showCalendarBottomSheet(context, currentStartTime);

    if ((currentEndTime != null &&
        result != null &&
        result.isAfter(currentEndTime))) {
      currentStartTime = currentEndTime;
    } else if (result != null) {
      currentStartTime = result;
    }
    isOpenTimeSelect = false;
    setState(() {});
  }

  void _onSelectEndDate() async {
    setState(() {
      isOpenTimeSelect = true;
    });
    DateTime result = await showCalendarBottomSheet(context, currentEndTime);
    if ((currentStartTime != null &&
        result != null &&
        result.isBefore(currentStartTime))) {
      currentEndTime = currentStartTime;
    } else if (result != null) {
      currentEndTime = result;
    }
    isOpenTimeSelect = false;
    setState(() {});
  }

  void _onApply() {
    widget.selectCallBack?.call(currentSelect);
    Navigator.of(context).pop({
      'startDate': currentStartTime,
      'endDate': currentEndTime,
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: getDp(17),
        ),
        _buildTop(S.current.sort_by_date_range),
        SizedBox(
          height: getDp(17),
        ),
        Padding(
          padding: EdgeInsets.symmetric(
            horizontal: getDp(10),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: sortTransactionList
                .map((e) => PressedOpacityButton(
                      onPressed: () => onChangeSalesTrend(e),
                      padding: EdgeInsets.symmetric(
                        vertical: getDp(10),
                        horizontal: getDp(34),
                      ),
                      child: NormalRadio(
                        title: e,
                        isSelect: currentSelect == e,
                      ),
                    ))
                .toList(),
          ),
        ),
        isShowCustom && !isOpenTimeSelect
            ? AnimatedContainer(
                key: ValueKey('Transaction DateTime'),
                duration: Duration(milliseconds: 500),
                padding: EdgeInsets.symmetric(vertical: getDp(10)),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    TimeSelectItem(
                        title: S.current.start_date,
                        value: currentStartTime == null
                            ? Config.settingInfo.dateFormat.toUpperCase() ??
                                'DD MMM YYYY'
                            : DateTimeUtils.formatGlobalDateTime(
                                currentStartTime),
                        onTap: _onSelectStartDate),
                    SizedBox(
                      height: getDp(16),
                    ),
                    TimeSelectItem(
                        title: S.current.end_date,
                        value: currentEndTime == null
                            ? Config.settingInfo.dateFormat.toUpperCase() ??
                                'DD MMM YYYY'
                            : DateTimeUtils.formatGlobalDateTime(
                                currentEndTime),
                        onTap: _onSelectEndDate),
                    SizedBox(
                      height: getDp(30),
                    ),
                    NormalButton(
                      onTap: enable ? _onApply : null,
                      title: S.current.apply,
                    )
                  ],
                ),
              )
            : AnimatedContainer(
                key: ValueKey('Transaction DateTime'),
                duration: Duration(milliseconds: 500),
                height: 0.0,
              ),
      ],
    );
  }

  Widget _buildTop(String title) => Container(
        height: getDp(32),
        color: aceWhiteColor,
        padding: EdgeInsets.symmetric(horizontal: getDp(24)),
        alignment: Alignment.centerLeft,
        child: Text(
          title,
          style: TextStyle(
            color: aceDarkGrayColor,
            fontSize: getSp(16),
            fontWeight: FontWeight.w400,
            height: 22 / 16,
          ),
        ),
      );
}
